<?php

namespace App\Console\Commands\Coupon;

use App\Kuafu\Activity\Model\ActivityModel;
use App\Kuafu\CustomerCoupon\Model\CustomerCouponModel;
use Illuminate\Console\Command;
use Illuminate\Support\Collection;

class FixCustomerCouponsAddSourceCommand extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'coupon:fixCustomerCouponsAddSourceCommand';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = '用户券包增加来源信息';

    /**
     * Create a new command instance.
     *
     * @return void
     */
    public function __construct()
    {
        parent::__construct();
    }

    /**
     * Execute the console command.
     *
     * @return int
     */
    public function handle()
    {
        $activityModel = ActivityModel::query()->withoutGlobalScope("isDel")->get();
        CustomerCouponModel::query()->chunkById(1000, function (Collection $collection) use ($activityModel) {
            $collection->each(function (CustomerCouponModel $customerCouponModel) use ($activityModel) {
                if ($customerCouponModel->activityId && empty($customerCouponModel->sourceName)) {
                    if ($customerCouponModel->source == CustomerCouponModel::SOURCE_ACTIVITY) {
                        $activity = $activityModel->where("id", $customerCouponModel->activityId)->first();
                        if ($activity) {
                            $this->output->comment($customerCouponModel->id);
                            $customerCouponModel->sourceName = $activity->name;
                            $customerCouponModel->save();
                        }
                    }
                }
            });
        });
        return 0;
    }
}
